<template>
  <div>
    {{ iframeUrl }}
    <!-- :src="pageData.iframeUrl + pageData.iframeQuery" -->
    <iframe
      ref="iframeRef"
      :src="iframeUrl"
      :style="{ width: '100%', height: iframeHeight }"
      frameborder="no"
      border="0"
      marginwidth="0"
      marginheight="0"
    ></iframe>
  </div>
</template>

<script setup>
  import { reactive, ref, nextTick, watch, onMounted, toRefs, onBeforeUnmount } from 'vue';
  import { useRouter } from 'vue-router';
  import { getToken } from '@/utils/auth';
  import { getIframeUrl } from '@/utils/iframeConfig';
  import {
    getVersionList,
    getDocumentDetail,
    getProperties,
    updateForm,
    documentPublish,
    getPresetFields,
    updatePresetFields,
  } from 'src/api/docReport/index.js';

  const router = useRouter();
  const props = defineProps({
    docInfoId: {
      type: [String, Number],
      default: '',
    },
  });

  const documentInfoId = ref(props.docInfoId);
  const viewItem = {};
  const token = getToken();

  const iframeUrl = `${getIframeUrl()}editor?documentInfoId=${
    documentInfoId.value
  }&token=${token}&bizModule=NursingHandbook`;

  const pageData = reactive({
    iframeQuery: '',
    actType: '', //view-设计，create-新建
    createFormData: {},
    formName: '',
    versionList: [], //版本列表
  });

  const iframeRef = ref(null);
  const iframeHeight = ref(document.documentElement.clientHeight - 60 + 'px');
  const postMsg = ({ type, data }) => {
    if (!iframeRef.value) return;
    iframeRef.value.contentWindow.postMessage({ type, data }, '*');
  };
  const handleFn = async (e) => {
    console.log(e);
    const { type, data: msgData } = e.data;
    switch (type) {
      // 文档详情
      case 'getDocumentDetail':
        // 文档详情  /document/detail
        try {
          const data = await getDocumentDetail({
            documentInfoId: msgData.documentInfoId,
            documentId: msgData.documentId,
            bizModule: 'NursingHandbook',
          });
          postMsg({ type, data });
        } catch (error) {
          console.error(error);
        }
        break;
      case 'getProperties':
        // 报告可选字段列表
        try {
          const data = await getProperties();
          postMsg({ type, data });
        } catch (error) {
          console.error(error);
        }
        break;
      case 'getVersionList':
        // 版本列表
        try {
          const data = await getVersionList(documentInfoId.value);
          postMsg({ type, data });
        } catch (error) {
          console.error(error);
        }
        break;

      case 'documentUpdate':
        // 保存草稿/暂存
        try {
          const data = await updateForm({
            ...msgData,
            bizModule: 'NursingHandbook', //模块名称固定为AdverseEventReport
            attribute: {
              id: msgData.documentId,
            },
          });
          postMsg({ type, data });
        } catch (error) {
          console.error(error);
        }
        break;
      case 'documentPublish':
        // 发布
        try {
          const data = await documentPublish({
            ...msgData,
            bizModule: 'NursingHandbook', //模块名称固定为AdverseEventReport
            attribute: {
              id: msgData.documentId,
            },
            usable: true,
          });
          postMsg({ type, data });
        } catch (error) {
          console.error(error);
        }
        break;
      case 'goBack':
        postMsg(type, {});
        router.push({ path: '/SystemSetting/reportTemplate' });
        // 报告可选字段列表
        break;
      case 'getPresetFields':
        // 获取表单上报时需要进行通信的字段
        try {
          const data = await getPresetFields();
          postMsg({ type, data });
        } catch (error) {
          console.error(error);
        }
        break;
      case 'updatePresetFields':
        // 发布表单字段说明与编码
        try {
          const data = await updatePresetFields(msgData);
          postMsg({ type, data });
        } catch (error) {
          console.error(error);
        }
        break;
      default:
        break;
    }
  };

  const initPage = () => {
    pageData.actType = router.currentRoute.value.query.actType;
    if (pageData.actType == 'view') {
      pageData.formName = viewItem.formName;
    } else {
      pageData.formName = '测试';
    }
    pageData.iframeQuery =
      'formName=' +
      pageData.formName +
      '&documentInfoId=' +
      documentInfoId.value +
      '&token=' +
      pageData.token;
  };

  initPage();
  onMounted(() => {
    window.addEventListener('message', handleFn);
  });
  onBeforeUnmount(() => {
    window.removeEventListener('message', handleFn);
  });
  watch(
    () => props.docInfoId,
    (newVal, oldVal) => {
      documentInfoId.value = newVal;
      initPage();
      nextTick();
    },
  );
</script>

<style lang="scss" scoped></style>
